package com.qmhl.toolposition.fragment

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.amap.api.location.AMapLocationClient
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.qmhl.toolposition.R
import com.qmhl.toolposition.activity.AddPositionActivity
import com.qmhl.toolposition.activity.CommitFeedbackActivity
import com.qmhl.toolposition.activity.SmoothBeforeActivity
import com.qmhl.toolposition.activity.SmoothMoveActivity
import com.qmhl.toolposition.databinding.FragmentAppPositionBinding
import com.qmhl.toolposition.enu.CatSmooth
import com.qmhl.toolposition.event.PositionEvent
import com.qmhl.toolposition.event.TabSelectEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.Date


class AppPositionFragment : Fragment() {

    private lateinit var binding: FragmentAppPositionBinding
    private lateinit var aMap: AMap
    private lateinit var positionEvent: PositionEvent
    private var isAddMarker = false


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAppPositionBinding.inflate(inflater, container, false)
        //高德地图更新隐私合规状态,需要在初始化地图之前完成
        AMapLocationClient.updatePrivacyShow(context, true, true);
        AMapLocationClient.updatePrivacyAgree(context, true);
        binding.mapView.onCreate(savedInstanceState)
        initData()
        initListener()
        return binding.root
    }

    private fun initListener() {
        binding.llAddFriend.setOnClickListener {
            startActivity(Intent(context, AddPositionActivity::class.java))
        }
        binding.llTravel.setOnClickListener {
            var intent = Intent(context, SmoothBeforeActivity::class.java)
            intent.putExtra("type", CatSmooth.ME.type)
            intent.putExtra("nickname", "我自己")
            startActivity(intent)
        }
    }

    private fun initData() {

        EventBus.getDefault().register(this)
        aMap = binding.mapView.map
        //显示定位蓝点
//        setPositionPoint()
        //地图相关设置
        mapSetting()
    }


    fun addMarker() {
        val markerOption = MarkerOptions()
        markerOption.position(LatLng(positionEvent.latitude, positionEvent.longitude))
//        markerOption.title("西安市").snippet("西安市：34.341568, 108.940174")

        markerOption.draggable(false) //设置Marker可拖动
        markerOption.rotateAngle(330f) //设置 Marker覆盖物的图片旋转角度，从正北开始，逆时针计算

        markerOption.icon(
            BitmapDescriptorFactory.fromBitmap(
                BitmapFactory.decodeResource(resources, R.mipmap.icon_position_me)
            )
        )

        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
        markerOption.isFlat = true //设置marker平贴地图效果


        val marker = aMap.addMarker(markerOption)
        isAddMarker = true
    }


    fun moveMarker() {
        val cameraPosition =
            CameraPosition(LatLng(positionEvent.latitude, positionEvent.longitude), 15f, 0f, 30f)
        val cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition)
        aMap.moveCamera(cameraUpdate)
    }


    private fun mapSetting() {

        val setting = aMap.uiSettings
        setting.isZoomControlsEnabled = false
        setting.isRotateGesturesEnabled = false//旋转手势
        setting.isTiltGesturesEnabled = false//倾斜手势


        //地图的缩放级别一共分为 17 级，从 3 到 19。数字越大，展示的图面信息越精细
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16f))


        aMap.uiSettings.setLogoBottomMargin(-50)//隐藏高德logo

    }

    /**
     * 参考网址 https://lbs.amap.com/api/android-sdk/guide/create-map/mylocation
     * **/
    private fun setPositionPoint() {
        val myLocationStyle = MyLocationStyle()
        //初始化定位蓝点样式类  连续定位、且将视角移动到地图中心点，
        // 定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE)
        myLocationStyle.interval(2000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_people))
        aMap.setMyLocationStyle(myLocationStyle) //设置定位蓝点的Style

        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true) // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。


    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public fun onPositionEvent(event: PositionEvent) {
        binding.tvPosition.text = event.address
        positionEvent = event
        if (!isAddMarker) {
            addMarker()
            moveMarker()
        }
        var sdf = SimpleDateFormat()
        sdf.applyPattern("yyyy-MM-dd HH:mm")
        var formatTime = sdf.format(Date())
        binding.tvTime.text = formatTime
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public fun onTabSelectEvent(event: TabSelectEvent) {
        if (event.position != 1) {
            moveMarker()
        }

    }


    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)

    }


}